var redis = require('redis');
var extend = require('extend');
var q = require('q');
var request = require('request').defaults({
    json: true
});
var mix = require('./../utility/mix.js');
var config = require('./../config.json');

/** 
 * @constructor
 * @param {number} prjId 项目Id
 */
var Project = function Project(prjId) {
    this.prjId = prjId || 1;
};
mix(Project, require('./Project.MonitorPoints.js'));
mix(Project, require('./Project.Layer.js'));
mix(Project, require('./Project.Status.js'));

/** 
 * @todo
 * 预先定义的工程类型,应该从数据库读取
 */
Project.preDefineTypes = [
    {
        typeCode: 'MetroMonitor',
        typeName: '监护项目',
        markerColor: 'red'
    }, {
        typeCode: 'LongTermSubElevation',
        typeName: '长期沉降',
        markerColor: 'darkred'
    }, {
        typeCode: 'LongTermSubChord',
        typeName: '长期收敛',
        markerColor: 'darkred'
    }, {
        typeCode: 'CriticalSectionMonitor',
        typeName: '重点段',
        markerColor: 'darkgreen'
    }, {
        typeCode: 'RoadTunnelMonitor',
        typeName: '公路隧道',
        markerColor: 'darkpurple'
    }, {
        typeCode: 'Volkswagen',
        typeName: '大众汽车',
        markerColor: 'cadetblue'
    }];

/** 
 * 获取前端项目所需的项目列表,一般从缓存中读取
 * @param {string} type 项目类型
 * @return {Promise} 工程列表
 */
Project.getFrontProjects = function (params) {
    var type = params.type || "MetroMonitor";
    var redisClient = redis.createClient();
    var redisKey = config.redisNamespace + ":" + type.charAt(0).toLowerCase() + type.slice(1);
    var defer = q.defer();
    redisClient.get(redisKey, function (err, reply) {
        if (err) {
            throw Error('获取前端缓存项目出错');
        }
        while (typeof reply === 'string') {
            reply = JSON.parse(reply);
        }
        defer.resolve(reply);
        redisClient.quit();
    })
    return defer.promise;
}

module.exports = Project;